#!/bin/bash

echo "🔍 MongoDB Sync Diagnosis Tool"
echo "=============================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查 Docker 容器状态
echo ""
print_info "1. Checking Docker container status..."
docker-compose -f docker-compose-fixed.yml ps

# 检查网络连接
echo ""
print_info "2. Checking network connectivity..."
if docker-compose -f docker-compose-fixed.yml exec mongodb-source ping -c 3 mongodb-target > /dev/null 2>&1; then
    print_success "Network connectivity between containers is OK"
else
    print_error "Network connectivity between containers failed"
fi

# 检查源数据库
echo ""
print_info "3. Checking source database..."
if docker-compose -f docker-compose-fixed.yml exec mongodb-source mongosh --username admin --password password1 --authenticationDatabase admin --eval "db.adminCommand('ping')" > /dev/null 2>&1; then
    print_success "Source database is accessible"
    
    # 检查副本集状态
    RS_STATUS=$(docker-compose -f docker-compose-fixed.yml exec mongodb-source mongosh --username admin --password password1 --authenticationDatabase admin --quiet --eval "rs.status().ok")
    if [ "$RS_STATUS" = "1" ]; then
        print_success "Source replica set is healthy"
    else
        print_warning "Source replica set may have issues"
    fi
    
    # 检查 Oplog
    OPLOG_SIZE=$(docker-compose -f docker-compose-fixed.yml exec mongodb-source mongosh --username admin --password password1 --authenticationDatabase admin --quiet --eval "db.getSiblingDB('local').oplog.rs.stats().size")
    print_info "Source oplog size: $OPLOG_SIZE bytes"
    
    # 检查测试数据
    USER_COUNT=$(docker-compose -f docker-compose-fixed.yml exec mongodb-source mongosh --username admin --password password1 --authenticationDatabase admin --quiet --eval "db.getSiblingDB('testdb').users.countDocuments()")
    print_info "Source users count: $USER_COUNT"
    
else
    print_error "Source database is not accessible"
fi

# 检查目标数据库
echo ""
print_info "4. Checking target database..."
if docker-compose -f docker-compose-fixed.yml exec mongodb-target mongosh --username admin --password password2 --authenticationDatabase admin --eval "db.adminCommand('ping')" > /dev/null 2>&1; then
    print_success "Target database is accessible"
    
    # 检查副本集状态
    RS_STATUS=$(docker-compose -f docker-compose-fixed.yml exec mongodb-target mongosh --username admin --password password2 --authenticationDatabase admin --quiet --eval "rs.status().ok")
    if [ "$RS_STATUS" = "1" ]; then
        print_success "Target replica set is healthy"
    else
        print_warning "Target replica set may have issues"
    fi
    
    # 检查测试数据
    USER_COUNT=$(docker-compose -f docker-compose-fixed.yml exec mongodb-target mongosh --username admin --password password2 --authenticationDatabase admin --quiet --eval "db.getSiblingDB('testdb').users.countDocuments()")
    print_info "Target users count: $USER_COUNT"
    
else
    print_error "Target database is not accessible"
fi

# 检查 mongosync 工具
echo ""
print_info "5. Checking mongosync tool..."
if docker-compose -f docker-compose-fixed.yml --profile sync run --rm mongosync mongosync --version > /dev/null 2>&1; then
    print_success "mongosync tool is available"
    VERSION=$(docker-compose -f docker-compose-fixed.yml --profile sync run --rm mongosync mongosync --version)
    print_info "mongosync version: $VERSION"
else
    print_error "mongosync tool is not available"
fi

# 检查权限
echo ""
print_info "6. Checking database permissions..."
SOURCE_PERMS=$(docker-compose -f docker-compose-fixed.yml exec mongodb-source mongosh --username admin --password password1 --authenticationDatabase admin --quiet --eval "db.runCommand({usersInfo: 'admin'})")
TARGET_PERMS=$(docker-compose -f docker-compose-fixed.yml exec mongodb-target mongosh --username admin --password password2 --authenticationDatabase admin --quiet --eval "db.runCommand({usersInfo: 'admin'})")

print_info "Source admin user permissions checked"
print_info "Target admin user permissions checked"

# 检查日志
echo ""
print_info "7. Recent container logs..."
echo "Source database logs (last 10 lines):"
docker-compose -f docker-compose-fixed.yml logs --tail=10 mongodb-source

echo ""
echo "Target database logs (last 10 lines):"
docker-compose -f docker-compose-fixed.yml logs --tail=10 mongodb-target

echo ""
print_info "Diagnosis completed!"
echo ""
print_info "Common issues and solutions:"
echo "1. If containers are not running: docker-compose -f docker-compose-fixed.yml up -d"
echo "2. If network issues: docker-compose -f docker-compose-fixed.yml down && docker-compose -f docker-compose-fixed.yml up -d"
echo "3. If authentication fails: check username/password in scripts"
echo "4. If oplog issues: ensure replica set is properly initialized"
echo "5. If sync fails: check mongosync version compatibility" 